package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.category

import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.View
import android.widget.ProgressBar
import androidx.collection.ArrayMap
import androidx.core.util.putAll
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.example.library_common.adapter.multi.AdapterViewItemViewClick
import com.example.library_common.adapter.multi.JssNewMultipleAdapter
import com.example.library_common.album.utils.Utils
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.LazyFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.category.bean.ClassifyMenuBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.category.recycler.modler.*
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.category.recycler.provider.GridContentProvider
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.category.recycler.provider.LinerHeaderProvider
import com.example.shushiyunsst.util.GOODS_DETAIL
import com.example.shushiyunsst.util.GOODS_LIST
import com.example.shushiyunsst.util.startNavigation
import ikidou.reflect.TypeBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class CategoryContentFragment : LazyFragment() {

    companion object {
        fun newInstance(): CategoryContentFragment {
            val args = Bundle()
            val fragment = CategoryContentFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
    }

    private lateinit var mRecyclerView: RecyclerView

    override fun getLayoutId() = R.layout.classify_content_fragment

    private lateinit var mAdapter: JssNewMultipleAdapter<ClassifyContentEntity>

    private val mData = mutableListOf<ClassifyContentEntity>()

    private val mDataMap = ArrayMap<String, List<ClassifyContentEntity>>()

    private var menuBean: ClassifyMenuBean? = null

    private lateinit var mProgressBar: ProgressBar

    fun setMenuBean(mBean: ClassifyMenuBean) {

        if (menuBean != null && mBean.cid == menuBean?.cid) return

        this.menuBean = mBean
        fillList()
    }


    override fun lazyInit() {

        if (menuBean == null) return

        fillList()

    }

    private fun parseDate(it: String?) {
        Log.d("parseDate", "parseDate: $it")

        val obj = JSON.parseObject(it)
        val any = obj["childCatList"]

        val array = JSON.parseArray(any.toString(), GridContent::class.java)
        mDataMap[(menuBean?.cid.toString())] = array
        loadList(array)
    }

    private fun loadList(array: Collection<ClassifyContentEntity>) {
        mData.addAll(array)
        mAdapter.notifyDataSetChanged()
        mProgressBar.visibility = View.GONE
    }

    private fun onFailed() {

    }

    override fun initView(view: View) {
        mProgressBar = view.findViewById(R.id.mProgressBar)

        mRecyclerView = view.findViewById(R.id.mRecyclerView)

        mRecyclerView.layoutManager =
            GridLayoutManager(_mActivity, SPAN_COUNT)

        mRecyclerView.setHasFixedSize(true)

        mAdapter = JssNewMultipleAdapter<ClassifyContentEntity>(mData)

        mRecyclerView.adapter = mAdapter

        mAdapter.lifecycle = lifecycle

        mAdapter.lifecycleOwner = this

        mAdapter.setSpanSizeInterface { _, _, position ->
            mAdapter.getItem(position).spanSize
        }

        registerAdapterItem()

        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position)
            if (item.itemType == GRID_CONTENT && item is GridContent) {
                ARouter.getInstance()
                    .build(GOODS_LIST)
                    .withString("categoryId", item.cid.toString())
                    .startNavigation(this)
            }

        }


    }


    private fun fillList() {

        mProgressBar.visibility = View.VISIBLE

        mAdapter.clears()

        val list = mDataMap[(menuBean?.cid.toString())]

        if (list != null) {
            loadList(list)
            return
        }

        val maps = mapOf(
            "catId" to menuBean?.cid,
        )
        RestClient.builder()
            .url(R.string.queryChildCatsByCatId)
            .raw(JSON.toJSONString(maps))
            .success {
                parseDate(it)

            }.failure {
                onFailed()
            }.error { _, _ ->
                onFailed()
            }
            .build()
            .post()

    }

    private fun registerAdapterItem() {
        mAdapter.register(GridContent::class.java, GridContentProvider::class.java)
//        mAdapter.register(LinerHeader::class.java, LinerHeaderProvider::class.java)
    }
}